# script to generate layout.yaml, which is used by a kicad plugin to set component positions, etc.
# plugin: https://github.com/mcbridejc/kicad_component_layout
#
# see pcb/README.md for more info

import math
from math import degrees, radians
import yaml
import sys
import os

# add parent dir to path so we can import oasis_constants
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
from oasis_constants import mainboard_usb_port_angle_deg


# COORDINATE SYSTEM NOTES
#
# The center of the board in KiCad is at (100, 100) as recorded in the `ORIGIN`
# variable below. All positions in the `components` mapping are *relative* to
# this origin. For example a component placed at (0, 0), will show up at
# (100, 100) in absolute coordinates in KiCad.
#
# Angles in `components` are in degrees and are clockwise from the +x axis.
# WARNING: this differs from the constants in oasis_constants, which are
# defined counter-clockwise from the +x axis.
#
ORIGIN = [100, 100]

# `components` contains an entry for each item that we would like to place
# programmatically. The code in this file adds entries to the mapping, then at
# the very end, writes `components` to a yaml file for import into kicad via
# the layout plugin.
components = {}

ARC_ORIGIN = [25, 100]
ARC_R = 92

# angle is in radians
def pos_at_angle_and_radius(angle, radius):
    x = round(radius * math.cos(angle), 3)
    y = round(radius * math.sin(angle), 3)
    rotation = degrees(-angle) + 90
    return (x, y, rotation)


# micro usb port
j2pos = pos_at_angle_and_radius(radians(-mainboard_usb_port_angle_deg), ARC_R - 2)
components["J2"] = {
    "location": j2pos[0:2],
    "rotation": j2pos[2],
}

layout = {
    "origin": ARC_ORIGIN,
    "components": components,
}

with open("layout.yaml", "w") as f:
    f.write("# DO NOT EDIT - this file was autogenerated by layout.py\n")
    f.write(yaml.safe_dump(layout, default_flow_style=None))
